package lab03.test06;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.*;

public class test {
    public static void main(String[] args) {
        String path = "D:\\Words.txt";

        RandomAccessFile randomAccessFile = null;

        Map<String, Integer> map = new HashMap<String, Integer>();

        try {
            randomAccessFile = new RandomAccessFile(path, "r");

            String line = null;
            while ((line = randomAccessFile.readLine()) != null) {
                System.out.println(line);
                /**
                 *  map
                 * key       value
                 * hello        2
                 * world        1
                 * man          0
                 */
                if (map.get(line) == null) {
                    map.put(line, 1);
                } else {
                    int value = map.get(line);
                    value = value + 1;
                    map.put(line, value);
                }

            }
            System.out.println("一共有" + map.size() + "互不相同个单词");

          /*  System.out.println("每个单词出现的频率为：");
            for (Map.Entry<String,Integer> entry :map.entrySet()){
                System.out.println(entry.getKey()+":"+entry.getValue());
            }*/

            List<Map.Entry<String, Integer>> infoIds = new ArrayList<Map.Entry<String, Integer>>(
                    map.entrySet());
            Collections.sort(infoIds, new Comparator<Map.Entry<String, Integer>>() {
                public int compare(Map.Entry<String, Integer> o1,
                                   Map.Entry<String, Integer> o2) {
                    return (o1.getValue() - o2.getValue());
                }
            });
            System.out.println("每个单词出现的频率为：");
            for (int i = 0; i < infoIds.size(); i++) {
                Map.Entry<String, Integer> ent = infoIds.get(i);
                System.out.println(ent.getKey() + "=" + ent.getValue());
            }


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                randomAccessFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
